<template>
  <el-dialog
    v-model="visible"
    :title="
      !dataForm.refundAddrId
        ? $t('shop.newShipAdd')
        : $t('shop.modifyShipAdd')
    "
    :close-on-click-modal="false"
    :width="750"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :inline="true"
      label-width="80px"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        class="addressee"
        :label="$t('publics.addressee')"
        prop="receiverName"
        :label-width="labelWidth"
      >
        <el-input
          v-model="dataForm.receiverName"
          :placeholder="$t('shop.consigneeName')"
          maxlength="30"
          style="width: 250px"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        :label="$t('publics.mobilePhone')"
        prop="receiverMobile"
        :label-width="labelWidth"
      >
        <el-input
          v-model="dataForm.receiverMobile"
          maxlength="11"
          style="width: 250px"
          :placeholder="$t('publics.mobilePhone')"
        />
      </el-form-item>

      <el-form-item
        class="mobilePhone"
        :label="$t('shop.companyLandline')"
        prop="receiverTelephone"
        :label-width="labelWidth"
      >
        <el-input
          v-model="dataForm.receiverTelephone"
          maxlength="36"
          style="width: 250px"
          show-word-limit
          :placeholder="$t('shop.companyLandline')"
        />
      </el-form-item>

      <el-form-item
        :label-width="labelWidth"
        :label="$t('address.postalCode')"
        prop="postCode"
      >
        <el-input
          v-model="dataForm.postCode"
          style="width: 250px"
          :placeholder="$t('address.postalCode')"
          maxlength="9"
        />
      </el-form-item>

      <el-form-item
        :label="$t('address.province')"
        prop="province"
        :label-width="labelWidth"
      >
        <el-col :span="8">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              style="width: 150px"
              @change="selectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="city">
            <el-select
              v-model="dataForm.cityId"
              :placeholder="$t('tip.select')"
              style="width: 150px"
              @change="selectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="area">
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
              style="width: 150px"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item
        :label-width="labelWidth"
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          :placeholder="$t('address.detailed')"
          maxlength="50"
          style="width: 600px"
        />
      </el-form-item>

      <el-form-item
        :label-width="labelWidth"
        :label="$t('address.defaultAddr')"
        prop=""
      >
        <el-checkbox v-model="defaultAddr">
          {{ $t('address.defaultAddr') }}
        </el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { Debounce } from '@/utils/debounce'

const emit = defineEmits(['refreshDataList'])
const dataForm = ref({
  refundAddrId: null,
  addrId: 0,
  addr: '',
  receiverName: '',
  receiverMobile: '',
  receiverTelephone: '',
  postCode: '',
  area: '',
  city: '',
  province: '',
  areaId: null,
  cityId: null,
  provinceId: null,
  defaultAddr: 0
})
const validateReceiverName = (rule, value, callback) => {
  if (!value.trim()) {
    dataForm.value.receiverName = ''
    callback(new Error($t('shop.coneeNameCanEmpty')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validatePhone = (rule, value, callback) => {
  if (!checkPhonePrefix()) {
    callback(new Error($t('shop.pleeNormaeNumF')))
  } else {
    callback()
  }
}
const validateAddr = (rule, value, callback) => {
  if (!value.trim()) {
    dataForm.value.addr = ''
    callback(new Error($t('shop.addressCannotBeEmpty')))
  } else {
    callback()
  }
}
const validateNumber = (rule, value, callback) => {
  if (value && !/^[1-9]\d*$/.test(value)) {
    callback(new Error($t('shop.pleaseInputNumber')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  receiverName: [
    { required: true, message: $t('shop.coneeNameCanEmpty'), trigger: 'blur' },
    { validator: validateReceiverName, trigger: 'blur' }
  ],
  addr: [{ required: true, message: $t('shop.addressCannotBeEmpty'), trigger: 'blur' },
    { validator: validateAddr, trigger: 'blur' }
  ],
  city: [{ required: true, message: $t('shop.cityCannotBeEmpty'), trigger: 'blur' }],
  province: [
    { required: true, message: $t('shop.provinceCannotBeEmpty'), trigger: 'blur' }
  ],
  area: [{ required: true, message: $t('shop.districtCounEmpty'), trigger: 'blur' }],
  receiverMobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  receiverTelephone: [{ validator: validateNumber, trigger: 'blur' }],
  postCode: [{ validator: validateNumber, trigger: 'blur' }]
})
const labelWidth = ref(localStorage.getItem('bbcLang') === 'en' ? '130px' : '80px')
let isSubmitting = false // 正在提交

onMounted(() => {

})

const defaultAddr = ref(false)
const visible = ref(false)
const dataFormRef = ref(null)
const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const init = (id, shopId) => {
  defaultAddr.value = false
  dataForm.value.refundAddrId = id || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.value.provinceId = null
    dataForm.value.cityId = null
    dataForm.value.areaId = null
    dataForm.value.shopId = shopId
  })
  // 等待地址信息返回
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  if (dataForm.value.refundAddrId) {
    http({
      url: http.adornUrl(
        `/shop/refundAddr/info/${dataForm.value.refundAddrId}`
      ),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value.addr = data.addr
      dataForm.value.receiverMobile = data.receiverMobile
      dataForm.value.receiverTelephone = data.receiverTelephone
      dataForm.value.areaId = data.areaId
      dataForm.value.cityId = data.cityId
      dataForm.value.provinceId = data.provinceId
      dataForm.value.receiverName = data.receiverName
      dataForm.value.postCode = data.postCode
      dataForm.value.defaultAddr = data.defaultAddr
      defaultAddr.value = data.defaultAddr === 1
      // 筛选出当前的市和区列表
      listAreaByParentId(data.provinceId).then(({ data }) => {
        cityList.value = data
      })
      listAreaByParentId(data.cityId).then(({ data }) => {
        areaList.value = data
      })
    })
  }
}
defineExpose({ init })

const checkPhonePrefix = () => {
  if (dataForm.value.receiverMobile) {
    const reg = /^1[3456789]\d{9}$/
    if (!reg.test(dataForm.value.receiverMobile)) {
      return false
    }
  }
  return true
}

const listAreaByParentId = (pid) => {
  let paramData = {}
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}

const getCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}

// 选择省
const selectProvince = (val) => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  areaList.value = []
  const { curNode, areas } = getCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}

// 选择市
const selectCity = (val) => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  const { curNode, areas } = getCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
// 表单提交
const onSubmit = Debounce(() => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
  // 将是否设为默认地址保存起来
  dataForm.value.defaultAddr = defaultAddr.value ? 1 : 0
  dataFormRef.value?.validate(valid => {
    if (valid) {
      if (isSubmitting) {
        return
      }
      isSubmitting = true
      http({
        url: http.adornUrl('/shop/refundAddr'),
        method: dataForm.value.refundAddrId ? 'put' : 'post',
        data: http.adornData({
          refundAddrId: dataForm.value.refundAddrId || undefined,
          addr: dataForm.value.addr,
          receiverName: dataForm.value.receiverName,
          receiverMobile: dataForm.value.receiverMobile,
          receiverTelephone: dataForm.value.receiverTelephone,
          area: dataForm.value.area,
          city: dataForm.value.city,
          province: dataForm.value.province,
          areaId: dataForm.value.areaId,
          cityId: dataForm.value.cityId,
          provinceId: dataForm.value.provinceId,
          postCode: dataForm.value.postCode,
          defaultAddr: dataForm.value.defaultAddr,
          shopId: dataForm.value.shopId
        })
      }).then(() => {
        isSubmitting = false
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList', page)
          }
        })
      }).catch(() => {
        isSubmitting = false
      })
    }
  })
}, 1500)

</script>

<style scoped lang="scss">
.addressee :deep(.el-input__inner) {
  padding-right: 45px !important;
}
.mobilePhone :deep(.el-input__inner) {
  padding-right: 45px !important;
}
</style>
